package com.cslc.wechat.common.action;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.cslc.wechat.util.SignUtil;

public class MainAction extends BaseAction {

	private static Logger logger = Logger.getLogger(MainAction.class);

	private RouteAction routeAction;
	public String execute() throws Exception {
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		HttpServletRequest request = this.request();
		logger.debug("接收用户请求的request信息:" + request);
		HttpServletResponse response = this.response();
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		// 接收参数微信加密签名、 时间戳、随机数
		String signature = request.getParameter("signature");
		logger.info("signature:" + signature);
		String timestamp = request.getParameter("timestamp");
		logger.info("timestamp:" + timestamp);
		String nonce = request.getParameter("nonce");
		logger.info("nonce:" + nonce);
		// 随机字符串
		String echostr = request.getParameter("echostr");
		logger.info("echostr:" + echostr);
		PrintWriter out = response.getWriter();
		// 请求校验
		if (signature == null || signature.length() <= 0)
			logger.error("signature为空！");
		else {
			if (SignUtil.checkSignature(signature, timestamp, nonce)) {
				logger.info("开始校验用户签名信息:" + signature);
				//Struts2判断GET/POST请求，POST接收处理消息，GET验证服务器地址有效性
				String method = ServletActionContext.getRequest().getMethod();
				if (method.equals("POST")) {
					out.print(echostr);
					// 调用核心服务类接收处理请求
					String respXml = routeAction.processRequest(request);
					logger.info("返回给用户的消息： \n" + respXml);
					out.print(respXml);
				} else if (method.equals("GET")) {
					out.print(echostr);
				} else{
					logger.error("错误的用户请求类型：" + method);
				}
			}
		}
		out.close();
		out = null;
		return null;
	}
	public RouteAction getRouteAction() {
		return routeAction;
	}
	public void setRouteAction(RouteAction routeAction) {
		this.routeAction = routeAction;
	}
}
